const express = require("express");
const app = express();
const request = require("request");
const bodyParser = require("body-parser");
require("dotenv").config();

const logger = require("./logger");

// const https = require('https');
// const http = require('http');
// const fs = require('fs');

// const options = {
//   key: fs.readFileSync('/etc/letsencrypt/live/devit.lk.caremybaby.ru/privkey.pem'),
//   cert: fs.readFileSync('/etc/letsencrypt/live/devit.lk.caremybaby.ru/fullchain.pem')
// };

app.use(express.static(__dirname + "/public"));

app.use("/node_modules", express.static(__dirname + "/node_modules"));

// console.log(__dirname + "/node_modules");
app.use(bodyParser.json({ limit: "256mb" }));
app.use(express.json({ limit: "256mb" })); // for parsing application/json
app.use(express.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

//----------------

const firstBlock = (string, request) => {
  const userAgent = request.headers["user-agent"];
  logger.info({ description: string, userAgent }, JSON.stringify(request.body));
};

const secondBlock = (string1, string2, response, error) => {
  if (error != null) {
    logger.error({ description: string1 }, error);
  }
  logger.info({ description: string2 }, response);
};

const thirdBlock = (string, response) => {
  logger.info({ description: string }, response);
};

app.use("/client", function (req, res) {
  firstBlock("request to /client:", req);

  const url = `https://crm.caremybaby.ru/Remotes/tgwa_pc_get_clients_jGHe73N?phoneNumber=%2B${req.body.clientPhone}&chatId=${req.body.chatId}`;

  request(url, function (error, response) {
    secondBlock(
      "error answer from /client:",
      "answer from Totum in /client:",
      response.body,
      error
    );
    thirdBlock("send response to request in /client:", response.body);
    res.send(response.body);
  });
});

app.use("/api/amount", function (req, res) {
  firstBlock("request to /api/amount:", req);

  let TestReturn = {};
  let sendAmount = req.body;
  let urlMoneta = "https://service.moneta.ru/services";

  request.post(
    {
      headers: {
        "content-type": "application/json",
      },
      url: urlMoneta,
      body: JSON.stringify({
        Envelope: {
          Body: {
            InvoiceRequest: {
              amount: sendAmount.MNT_AMOUNT,
              clientTransaction: sendAmount.MNT_TRANSACTION_ID,
              description: "Оплата за уроки",
              payee: process.env.MONETA_AMOUNT_NUMBER,
              payer: "card",
            },
          },
          Header: {
            Security: {
              UsernameToken: {
                Password: process.env.MONETA_PASS,
                Username: process.env.MONETA_USER,
              },
            },
          },
        },
      }),
    },
    function (error, response) {
      TestReturn = response.body;
      TestReturn =
        JSON.parse(TestReturn).Envelope.Body.InvoiceResponse.transaction;
      secondBlock(
        "error answer from /api/amount:",
        "answer from Moneta /client:",
        TestReturn,
        error
      );
      sendAmount["MNT_ID"] = TestReturn;
      sendAmount["status"] = "CREATED";
      request.post(
        {
          headers: {
            "content-type": "application/json",
          },
          url: "https://crm.caremybaby.ru/Remotes/lk__payments_Cm2Hs5O",
          body: JSON.stringify(sendAmount),
        },
        function (err, response) {
          secondBlock(
            "error answer from Totum creating a transaction /api/amount:",
            "answer from Totum in /api/amount:",
            response.body,
            err
          );
        }
      );
      thirdBlock("send response to request in /client:", TestReturn);
      res.json(TestReturn);
    }
  );
});

app.use("/newclient", function (req, res) {
  firstBlock("request to /newclient:", req);
  let sendBody = req.body;
  let returnJson = {};
  const createClientUrl = `https://api.yclients.com/api/v1/clients/1026208`;
  request.post(
    {
      headers: {
        "content-type": "application/json",
        Authorization:
          "Bearer stya95tkkjxcz2g857pp, User ebae5cbf61bf772a7ddcd5233cd4054a",
        Accept: "application/vnd.api.v2+json",
      },
      url: createClientUrl,
      body: JSON.stringify(sendBody),
    },
    function (error, response) {
      returnJson = response.body;
      secondBlock(
        "error answer from /newclient:",
        "Ответ от yclient /newclient:",
        returnJson,
        error
      );
    }
  );
  setTimeout(function () {
    thirdBlock("send response to request in /newclient:", returnJson);
    res.json(JSON.parse(returnJson));
  }, 550);
});

app.use("/sendcode", function (req, res) {
  console.log(req.body);
  firstBlock("request to /sendcode:", req);
  let textFromBot = `
  <b>Код подтверждения для входа в личный кабинет:</b> ${req.body.codeFromClient}%0A%0AЕсли Вы не запрашивали код, просто проигнорируйте или удалите это сообщение`;

  let url = `https://api.telegram.org/bot${process.env.BOT_TOKEN}/sendmessage?chat_id=${req.body.chatId}&text=${textFromBot}&parse_mode=HTML`;

  fetch(url)
    .then((response) => response.json())
    .then((data) => {
      console.log(data);
      thirdBlock("send response to request in /sendcode:", data);
      res.send(data);
    })
    .catch((error) => console.error("Error:", error));
});

app.post("/valute", (req, res) => {
  firstBlock("request to /valute:", req);

  const url = `https://crm.caremybaby.ru/Remotes/tgwa_pc_get_valute_KGug87s?client_group_id=${req.body.clientGroupId}`;
  request(url, function (error, response) {
    // console.log(response.body);

    secondBlock(
      "error answer from /valute:",
      "answer from Totum in /valute:",
      response.body,
      error
    );
    thirdBlock("send response to request in /valute:", response.body);
    res.send(response.body);
  });
});

app.get("/lesson", (req, res) => {
  firstBlock("request to /lesson:", req);
  const urlLesson = `https://crm.caremybaby.ru/Remotes/tgwa_pc_main_getmaterials_dsjUE67?request=lessons`;
  request(urlLesson, function (error, response) {
    // console.error("error:", error); // Print the error if one occurred

    secondBlock(
      "error answer from /lesson:",
      "answer from Totum in /lesson:",
      response.body,
      error
    );
    thirdBlock("send response to request in /lesson:", response.body);
    res.send(response.body);
  });
});

app.get("/materials", (req, res) => {
  firstBlock("request to /materials:", req);
  request(
    `https://crm.caremybaby.ru/Remotes/tgwa_pc_main_getmaterials_dsjUE67?request=materials`,
    function (error, response) {
      secondBlock(
        "error answer from /materials:",
        "answer from Totum in /materials:",
        response.body,
        error
      );
      thirdBlock("send response to request in /materials:", response.body);
      res.send(response.body);
    }
  );
});

app.get("/banners", (req, res) => {
  firstBlock("request to /banners:", req);
  request(
    `https://crm.caremybaby.ru/Remotes/tgwa_pc_main_getmaterials_dsjUE67?request=banners`,
    function (error, response) {
      secondBlock(
        "error answer from /banners:",
        "answer from Totum in /banners:",
        response.body,
        error
      );
      thirdBlock("send response to request in /banners:", response.body);
      res.send(response.body);
    }
  );
});

app.use("/nextlessons", (req, res) => {
  firstBlock("request to /nextlessons:", req);
  const urlLesson = `https://crm.caremybaby.ru/Remotes/tgwa_pc_get_records_QwhY655?request=next_lesson&client_number=${req.body.clientGroupId}`;
  request(urlLesson, function (error, response) {
    // console.error("error:", error); // Print the error if one occurred
    secondBlock(
      "error answer from /nextlessons:",
      "answer from Totum in /nextlessons:",
      response.body,
      error
    );
    thirdBlock("send response to request in /nextlessons:", response.body);
    res.send(response.body);
  });
});

app.use("/prevlessons", (req, res) => {
  firstBlock("request to /prevlessons:", req);
  const urlLesson = `https://crm.caremybaby.ru/Remotes/tgwa_pc_get_records_QwhY655?request=prev_lessons&client_number=${req.body.clientGroupId}`;

  request(urlLesson, function (error, response) {
    secondBlock(
      "error answer from /prevlessons:",
      "answer from Totum in /prevlessons:",
      response.body,
      error
    );
    thirdBlock("send response to request in /prevlessons:", response.body);
    res.send(response.body);
  });
});

app.use("/getrecords", (req, res) => {
  firstBlock("request to  /getrecords:", req);

  const urlRecords = `https://crm.caremybaby.ru/Remotes/tgwa_pc_get_records_QwhY655?client_group_id=${req.body.clientGroupId}`;

  request(urlRecords, function (error, response) {
    secondBlock(
      "error answer from /getrecords:",
      "answer from Totum in /getrecords:",
      response.body,
      error
    );
    thirdBlock("send response to request in /getrecords:", response.body);
    res.send(response.body);
  });
});

app.post("/feadbackstatus", (req, res) => {
  firstBlock("request to /feadbackstatus:", req);
  const urlFromCheckStatusFeadback = `https://crm.caremybaby.ru/Remotes/bot__getdata_jdDr41n?request=check_feedback&resource_id=${req.body.resourseId}`;

  request(urlFromCheckStatusFeadback, function (error, response) {
    secondBlock(
      "error answer from /feadbackstatus:",
      "answer from Totum in /feadbackstatus:",
      response.body,
      error
    );
    thirdBlock("send response to request in /feadbackstatus:", response.body);

    res.send(response.body);
  });
});

app.post("/cancellesson/text", (req, res) => {
  firstBlock("request to /cancellesson/text:", req);
  const cancelUrl = `https://crm.caremybaby.ru/Remotes/tgwa__pc_cancel_record_Mdh67He1?request=cancel_text&record=${req.body.resourceId}`;
  request(cancelUrl, function (error, response) {
    secondBlock(
      "error answer from /cancellesson/text:",
      "answer from Totum in /cancellesson/text:",
      response.body,
      error
    );
    thirdBlock(
      "send response to request in /cancellesson/text:",
      response.body
    );
    res.send(response.body);
  });
});

app.post("/cancellesson/action", (req, res) => {
  firstBlock("request to /cancellesson/action:", req);

  const urlCancelLesson = `https://crm.caremybaby.ru/Remotes/tgwa__pc_cancel_record_Mdh67He1?request=cancel_action&record=${req.body.resourceId}`;
  request(urlCancelLesson, function (error, response) {
    secondBlock(
      "error answer from /cancellesson/action:",
      "answer from Totum in /cancellesson/action:",
      response.body,
      error
    );
    thirdBlock(
      "send response to request in /cancellesson/text:",
      response.body
    );
    res.send(response.body);
  });
});

app.post("/sendfeadback", function (req, res) {
  firstBlock("request to /sendfeadback:", req);

  const sendUrl = `https://crm.caremybaby.ru/Remotes/bot__getdata_jdDr41n?request=new_feedback&feedback_mark=${req.body.rate}&feedback_text=${req.body.feadback}&resource_id=${req.body.resource_id}`;
  request(sendUrl, (error, response) => {
    secondBlock(
      "error answer from /sendfeadback:",
      "answer from Totum in /sendfeadback:",
      response.body,
      error
    );
    thirdBlock("send response to request in /sendfeadback:", response.body);
    res.send(response.body);
  });
});

app.use("/promo", (req, res) => {
  console.log(req.body);
  firstBlock("request to /promo:", req);
  const urlPromo = `https://crm.caremybaby.ru/Remotes/lk__promocodes_dSj2Ns?request=activate&promo=${req.body.promo}&client=${req.body.client}`;
  // let returnResp = "";

  request(urlPromo, function (error, response) {
    // returnResp = response.body;
    // console.log(JSON.parse(response.body));
    secondBlock(
      "error answer from /promo:",
      "answer from Totum in /promo:",
      response.body,
      error
    );
    thirdBlock("send response to request in /promo:", response.body);
    res.json(JSON.parse(response.body));
  });
});

//---------------

app.post("/api/form", function (req, res) {
  firstBlock("request to /api/form:", req);

  if (req.body.date !== undefined) {
    req.body.date = new Date(req.body.date).toLocaleDateString("ru-RU");
  }

  //const sendUrl = `https://crm.caremybaby.ru/Remotes/tgwa__pc_form_client_jnsfFAN234`;

  const sendBotMessegeTrialNoAuth = `
    <b>Новая заявка на занятие</b>%0A%0A
<b>Тип занятия:</b> ${req.body.requestType}%0A 
<b>Клиент:</b> ${req.body.clientName}%0A 
<b>Имя ребенка:</b> ${req.body.childName}%0A 
<b>Номер Телефона:</b> ${req.body.phoneNumber}%0A 
<b>Номер телеграмм:</b> ${req.body.client[0].tg_phone_plus}`;

  const sendBotMessegeTrialAuth = `
    <b>Новая заявка на занятие</b>%0A%0A`;

  const sendBotMessegeRegular = `
    <b>Новая заявка на занятие</b>%0A%0A
<b>Тип занятия:</b> ${req.body.requestType}%0A 
<b>Клиент:</b> ${req.body.client[0].client_name}%0A 
<b>Номер Телефона:</b> ${req.body.client[0].client_phone}%0A 
<b>Желаемое занятие:</b> ${req.body.lessonName}%0A 
<b>Дата время:</b> ${req.body.date} ${req.body.timesOfDay}%0A 
<b>Коментарий:</b> ${req.body.comment}%0A`;

  // let flag = true

  if (req.body.requestType === "Пробное занятие не авторизован") {
    const botUrlMen = `https://api.telegram.org/bot${process.env.BOT_TOKEN}/sendmessage?chat_id=${process.env.CHAT_ID_MENEGER}&text=${sendBotMessegeTrialNoAuth}&parse_mode=HTML`;

    fetch(botUrlMen)
      .then((response) => response.json())
      .then((data) => {
        secondBlock("answer from bot/api/movelesson:", data);
        thirdBlock("send response to request in /api/form:", data.ok);
        res.send(data.ok);
      })
      .catch((err) => console.log(err));
  } else if (
    req.body.client[0].staff_status === "Менеджер" ||
    req.body.client[0].staff_status === "n/a"
  ) {
    const botUrlMen = `https://api.telegram.org/bot${process.env.BOT_TOKEN}/sendmessage?chat_id=${process.env.CHAT_ID_MENEGER}&text=${sendBotMessegeRegular}&parse_mode=HTML`;
    fetch(botUrlMen)
      .then((response) => response.json())
      .then((data) => {
        secondBlock("answer from bot/api/movelesson:", data);
        thirdBlock("send response to request in /api/form:", data.ok);
        res.send(data.ok);
      })
      .catch((err) => console.log(err));
  } else {
    const botUrlCoor = `https://api.telegram.org/bot${process.env.BOT_TOKEN}/sendmessage?chat_id=${process.env.CHAT_ID_COORDINATOR}&text=${sendBotMessegeRegular}&parse_mode=HTML`;
    fetch(botUrlCoor)
      .then((response) => response.json())
      .then((data) => {
        secondBlock("answer from bot/api/movelesson:", data);
        thirdBlock("send response to request in /api/form:", data.ok);
        res.send(data.ok);
      })
      .catch((err) => console.log(err));
  }

  // setTimeout(() => {
  //   thirdBlock("send response to request in /api/form:", sendAnswer);
  //   res.send(sendAnswer);
  // }, 650);
});

app.post("/api/movelesson", function (req, res) {
  firstBlock("request to /api/movelesson:", req);
  req.body.date = new Date(req.body.date).toLocaleDateString("ru-RU");

  const sendTextBotService = `
<b>Клиент просит перенести занятие</b>%0A%0A
<b>Имя:</b> ${req.body.client[0].client_name}%0A
<b>Занятие</b>: ${req.body.lessonName} ${req.body.lesson.lesson_date} 
<b>Новая дата:</b> ${req.body.date}%0A
<b>Комментарий:</b> ${req.body.comment}%0A
<b>Номер телефона:</b> ${req.body.client[0].client_phone}`;

  let urlService = "";

  if (
    req.body.client[0].staff_status === "Менеджер" ||
    req.body.client[0].staff_status === "n/a"
  ) {
    urlService = `https://api.telegram.org/bot${process.env.BOT_TOKEN}/sendmessage?chat_id=${process.env.CHAT_ID_MENEGER}&text=${sendTextBotService}&parse_mode=HTML`;
  } else {
    urlService = `https://api.telegram.org/bot${process.env.BOT_TOKEN}/sendmessage?chat_id=${process.env.CHAT_ID_COORDINATOR}&text=${sendTextBotService}&parse_mode=HTML`;
  }

  fetch(urlService)
    .then((response) => response.json())
    .then((data) => {
      secondBlock("answer from bot/api/movelesson:", data);

      thirdBlock("send response to request in /api/movelesson:", data.ok);
      res.send(data.ok);
    })
    .catch((err) => console.log(err));
});

app.post("/late-messages", function (req, res) {
  firstBlock("request to /late-messages:", req);
  const returnReq = req.body;
  const parser = returnReq.client;

  let teacherChatId = returnReq.teacher_tg_id;

  let sendTextBotPedago = `
	%09<b>Клиент опаздывает на занятие</b>%0A%0A
<b>Имя клиента:</b> ${parser[0].client_name}%0A
<b>Занятие:</b> ${returnReq.lesson_name}%0A
<b>Время:</b> ${returnReq.lesson_date}`;

  let sendTextBotService = `
  %09 <b>Клиент опаздывает на занятие</b>%0A%0A
<b>Имя клиента:</b> ${parser[0].client_name}%0A
<b>Занятие:</b> ${returnReq.lesson_name}%0A
<b>Время:</b> ${returnReq.lesson_date}%0A
<b>Педагог:</b> ${returnReq.teacher}%0A
<b>Филиал:</b> ${returnReq.company_id}`;

  let urlPedago = `https://api.telegram.org/bot${process.env.BOT_TOKEN}/sendmessage?chat_id=${teacherChatId}&text=${sendTextBotPedago}&parse_mode=HTML`;
  let urlService = "";

  if (
    parser[0].staff_status === "Менеджер" ||
    parser[0].staff_status === "n/a"
  ) {
    urlService = `https://api.telegram.org/bot${process.env.BOT_TOKEN}/sendmessage?chat_id=${process.env.CHAT_ID_MENEGER}&text=${sendTextBotService}&parse_mode=HTML`;
  } else {
    urlService = `https://api.telegram.org/bot${process.env.BOT_TOKEN}/sendmessage?chat_id=${process.env.CHAT_ID_COORDINATOR}&text=${sendTextBotService}&parse_mode=HTML`;
  }

  fetch(urlPedago)
    // .then((response) => response.json())
    // .then((data) => {
    //
    // })
    .catch((err) => console.log(err));
  fetch(urlService)
    .then((response) => response.json())
    .then((data) => {
      secondBlock("answer from bot/api/movelesson:", data);

      thirdBlock("send response to request in /api/movelesson:", data.ok);
      res.send(data.ok);
    })
    .catch((err) => console.log(err));

});

app.use("/totum/request", (req, res) => {
  const returnReqeust = req.body;
  for (let i = 0; i < returnReqeust.length; i++) {
    const obj = {};
    for (let j = 0; j < returnReqeust[i].hours.length; j++) {
      if (obj[returnReqeust[i].hours[j]]) {
        obj[returnReqeust[i].hours[j]]++;
      } else {
        obj[returnReqeust[i].hours[j]] = 1;
      }
    }
    returnReqeust[i].hours = obj;
  }
  setTimeout(() => {
    res.json(returnReqeust);
  }, 300);
});

const port = 3001;

app.listen(port, () => {
  console.log(`Example app listening on port http://localhost:${port}`);
});

// https.createServer(options, app).listen(443);

//----------Подключение к БД
// const { Client } = require("pg");

// const client = new Client({
//   host: "localhost",
//   user: "postgres",
//   password: "4816",
//   database: "test",
//   port: 5433,
// });

// client
//   .connect()
//   .then(() => console.log("Connected to PostgreSQL"))
//   .catch((err) => console.error("Connection error", err.stack));

// let allClient = {};

// function queryDatabase() {
//   console.log(`Running query to PostgreSQL server: ${client.host}`);

//   const query = "SELECT * FROM person";

//   client
//     .query(query)
//     .then((res) => {
//       const rows = res.rows;
//       allClient = rows;
//       rows.map((row) => {
//         // console.log(`Read: ${JSON.stringify(row)}`);
//       });

//       //   process.exit();
//     })
//     .catch((err) => {
//       console.log(err);
//     });

//   //   setTimeout(() => {
//   //     console.log("all", allClient);
//   //   }, 1000);
// }

// queryDatabase();

//-------------------
